package cn.itcast.solr;

import cn.itcast.domain.Item;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.junit.Test;

import java.util.List;
import java.util.Map;

public class SolrPageQuery {
    /**
     * @Description:使用Solrj查询索引，并且实现分页
     *
     * @Author:fsy
     * @Date:2018/3/2
     */
    @Test
    public void testPageQuuery() throws SolrServerException {
        //准备分页的参数
        int currentPage = 2;//当前页
        final int PAGE_SIZE = 5;//每页显示的数据
        int start = (currentPage - 1) * PAGE_SIZE;// 当前页的起始条数

        //连接服务器
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/core1");
        //查询条件对象
        SolrQuery solrQuery = new SolrQuery("title:手机");
        //设置分页信息到查询对象中
        solrQuery.setStart(start);
        solrQuery.setRows(5);

        //执行查询，获取响应
        QueryResponse response = solrServer.query(solrQuery);
        // 获取查询结果,指定实体类的类型，返回实体类的集合
        List<Item> items = response.getBeans(Item.class);
        for (Item item : items) {
            System.out.println(item);
        }
        System.out.println("分页查询完成");
    }

    @Test
    public  void testHighlightingQuery() throws SolrServerException {
        //连接服务器
        SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/core1");
        //创建查询对象
        SolrQuery solrQuery = new SolrQuery("title:手机");
        //设置高亮标签
        solrQuery.setHighlightSimplePre("<em>");
        solrQuery.setHighlightSimplePre("</em>");
        solrQuery.addHighlightField("title");

        //查询
        QueryResponse response = solrServer.query(solrQuery);
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        // 获取非高亮结果
        List<Item> list = response.getBeans(Item.class);
        for (Item item : list) {
            String id = item.getId();
            System.out.println("id: " + id);
            System.out.println("title: " + highlighting.get(id).get("title").get(0));
            System.out.println("price: " + item.getPrice());
        }
    }

}
